# include "queue.h"

Queue * newQueue () {
	Queue *new = (Queue *) malloc(sizeof(Queue));
	if (!new) logMessage("util.lists","queue","newQueue","Memória Insuficiente",CRITICAL);
	new->in = new->out = NULL;
	new->elems = 0;
	return new;
}

LinkedList * queueToLinkedList (Queue *q) {
	if (!q) return NULL;
	return q->in;
}
Queue * linkedLinkedListToQueue (LinkedList *list) {
	Queue *new = newQueue();
	new->in = new->out = list;
	if (!list) return new;
	LinkedList *parent = NULL,*aux = list;
	while (aux->next) {
		aux = nextElem(aux);
	}
	new->out = aux;
	return new;
}

int enqueue (Queue *q, void *data) {
	LinkedList *elem;
	if (!q) return 0; 
	if (q->in == NULL) q->in = q->out = insertElemHead(q->in,data);
	else {
		elem = newElem();
		if (!elem) return 0;
		elem->data = data;
		elem->next = NULL;
		q->in->next = elem;
		q->in = elem;
	}
	q->elems++;
	return 1;
}

void * dequeue (Queue *q) {
	if (!q||!q->out) return NULL;
	if (!q->elems) return NULL;
	LinkedList *elem = q->out;
	q->elems--;
	if (!q->elems) q->in = NULL;
	q->out = nextElem(q->out);
	void *data = getData(elem);
	free(elem);
	return data;
}

void * peek (Queue *q) {
	if (!q||!q->out) return NULL;
	else return getData(q->out);
}

void freeQueue (Queue *q) {
	if (q) {
		if (q->out) freeLinkedList(q->out);
		free(q);
	}
}
